package biznussoft.fieldservice360.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.adapter.MyActivitesServiceAdapter;
import biznussoft.fieldservice360.listeners.InventoryListener;
import biznussoft.fieldservice360.model.ActivityModel;
import biznussoft.fieldservice360.model.Bean_Class;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class MyActivitiesMasterFragment  extends BaseFragment implements OnItemClickListener{
	private ListView lv;
	private InventoryListener mListener; 
	static HashMap<String, ArrayList<ActivityModel>> mActivityDetailsList;
	private RestClient client;
	static ArrayList<ActivityModel> myActivitiesserviceOrderSubList;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mListener = (InventoryListener) getActivity();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.inventory, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		client =  HomeActivity.mActivity.client;
		Bean_Class.api_Version = getString(R.string.api_version);
		retriveActivities();
		lv = (ListView) getView().findViewById(R.id.listview);
		lv.setOnItemClickListener(this);
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);


		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		//		getActivity().registerReceiver(mReceiver, new IntentFilter("RESPONSE"));
		super.onResume();
	}
	@Override
	public void onDestroy() {
		//		getActivity().unregisterReceiver(mReceiver);
		super.onDestroy();
	}


	public void retriveActivities(){
		try{
			String serviceOrder = "SELECT Name,Id,FConnect__Contact_Name__c,FConnect__Account_Name__c,FConnect__Account__c,FConnect__Adress__c,FConnect__Billable__c,FConnect__Bill_To_Address__c,FConnect__Contact__c,FConnect__Site_Name__c,FConnect__No_Of_Activities__c,FConnect__Alternate_Phone__c,FConnect__Priority__c,FConnect__Status__c,FConnect__Start_Date__c,FConnect__Installed_Product2__c,FConnect__Warranty_used__c,FConnect__Agreement__c,FConnect__Entitlement_Plan_Name__c,FConnect__Product_ID__c,FConnect__Service__c,FConnect__Agreement_Line__c,FConnect__Service_Discription__c,FConnect__Product_ID2__c,Agreement_Name__c,Entitlement_Group_Name__c,Service_Name__c,(SELECT Id,Name,FConnect__Activity__c,FConnect__Status__c,FConnect__Planned_End_Date_Time__c,FConnect__Planned_Start_DateTime__c,FConnect__Duration__c,FConnect__Billable__c,Activity_Name__c,Technician_Id__c,Site__c FROM FConnect__Activities__r) FROM FConnect__Service_Order__c";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {

						JSONObject jsonObject1 = new JSONObject(result         
								.toString());

						JSONArray jsonArray = jsonObject1
								.getJSONArray("records");


						Gson _gson = new Gson();
						myActivitiesserviceOrderSubList = new ArrayList<ActivityModel>();
						for (int i = 0; i < jsonArray.length(); i++) {

							if (!jsonArray.isNull(i)) {



								JSONObject siteObject = jsonArray.getJSONObject(i);
								try{
									if (siteObject.getJSONObject("FConnect__Activities__r") != null) {
										JSONArray siteArray = siteObject.getJSONObject("FConnect__Activities__r").getJSONArray("records");

										for (int j = 0; j < siteArray.length(); j++) {
											if (!siteArray.isNull(j)) {
												ActivityModel bean1 = _gson.fromJson(
														siteArray.getString(j),
														ActivityModel.class);
												
											
												myActivitiesserviceOrderSubList.add(bean1);
											}

										}
									}
								}catch (Exception e) {
								}


							}

						}

						showRecords();

					} catch (Exception e) {

						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

	}


	public void showRecords(){
		MyActivitesServiceAdapter adapter = new MyActivitesServiceAdapter(getActivity(),myActivitiesserviceOrderSubList);
		lv.setAdapter(adapter);
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1,  int position, long arg3) {
		// TODO Auto-generated method stub

		//setHasOptionsMenu(false);
		switch (arg0.getId()) {
		case R.id.listview:
			setHasOptionsMenu(false);
			mListener.onWarehouseClicked(position);

			break;

		default:
			break;
		}


	}


}
